/* 
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.avdheshyadav.p4j.sample.server.handler;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import com.avdheshyadav.p4j.common.DAOException;
import com.avdheshyadav.p4j.sample.server.dao.LibraryDataRepository;
import com.avdheshyadav.p4j.sample.server.dao.StudentRepository;
import com.avdheshyadav.p4j.sample.shared.data.Student;
import com.avdheshyadav.p4j.sample.shared.rpc.FetchStudents;
import com.avdheshyadav.p4j.sample.shared.rpc.StudentsResult;
import com.google.inject.Inject;

public class FetchStudentsHandler implements ActionHandler<FetchStudents, StudentsResult>
{
	private final LibraryDataRepository dataRepository;

	@Inject
	public FetchStudentsHandler(final LibraryDataRepository dataRepository)
	{
		this.dataRepository = dataRepository;
	}

	@Override
	public StudentsResult execute(final FetchStudents action, final ExecutionContext context) throws ActionException 
	{
		StudentRepository studentRepository = dataRepository.getStudentRepository();
		List<Student> students = new ArrayList<Student>();	
		try 
		{
			students = (List<Student>)studentRepository.findAll(Student.class, studentRepository.initialPosition, studentRepository.ALL_ROWS);
		} catch (DAOException e) 
		{
			e.printStackTrace();
		}
		StudentsResult result = new StudentsResult(students);
		return result;
	}


	@Override
	public void rollback(final FetchStudents action,final StudentsResult result, final ExecutionContext context)throws ActionException 
	{
		// Nothing to do here
	}

	@Override
	public Class<FetchStudents> getActionType() 
	{
		return FetchStudents.class;
	}
}
